import React, { useState, useEffect } from 'react'
import PropTypes from 'prop-types'
import classNames from 'classnames'
import Input from '../Input'
import Select from '../Select'

const calculatePage = (total, pageSize) => Math.ceil(total / pageSize)
const getNumValue = (num, defaultVal) => (!num || isNaN(num)) ? defaultVal : +num
const getDisplayOptions = (options) => {
  return options.map(option => {
    return { value: option, label: `${option} 条/页` }
  })
}

const Pagination = ({
  total,
  current,
  pageSize,
  defaultCurrent,
  defaultPageSize,
  showSizeChanger,
  showQuickJumper,
  showTotal,
  pageSizeOptions,
  disabled,
  onShowSizeChange,
  onChange,
  RANGE,
  ...rest
}) => {
  const [curPage, setCurPage] = useState(current ?? defaultCurrent)
  useEffect(() => { current !== undefined && setCurPage(current) }, [current])
  const handlePageChange = (page) => {
    if (page > allPage) {
      page = allPage
    }
    if (page < 1) {
      page = 1
    }

    if (current === undefined) setCurPage(page)
    onChange && onChange(page, pageSize)
  }

  const [curSize, setCurSize] = useState(pageSize ?? defaultCurrent)
  useEffect(() => pageSize !== undefined ? setCurSize(pageSize) : undefined, [pageSize])
  const handleSizeChange = (size) => {
    const newAllPage = calculatePage(total, size)
    const page = curPage > newAllPage ? newAllPage : curPage
    if (!current) {
      setCurPage(page)
    }
    if (!pageSize) {
      setCurSize(size)
    }
    onShowSizeChange && onShowSizeChange(page, size)
  }

  const allPage = calculatePage(total, curSize)
  let left = Math.max(1, curPage - RANGE);
  let right = Math.min(curPage + RANGE, allPage);
  if (curPage - 1 < RANGE) {
    right = 1 + RANGE * 2
  }
  if (allPage - curPage < RANGE) {
    left = allPage - RANGE * 2
  }
  let arr = []
  for (let index = left; index <= right; index++) {
    arr.push({ value: index, type: 'num' })
  }
  if (curPage - 1 >= RANGE * 2) {
    arr.unshift({ value: '...', type: 'jumpPrev' })
  }
  if (allPage - curPage >= RANGE * 2) {
    arr.push({ value: '...', type: 'jumpNext' })
  }
  if (left !== 1) {
    arr.unshift({ value: 1, type: 'num' });
  }
  if (right !== allPage) {
    arr.push({ value: allPage, type: 'num' });
  }
  arr.unshift({ value: '<', type: 'prev' })
  arr.push({ value: ">", type: 'next' })

  const range = [1 + (curPage - 1) * curSize, curPage * curSize]
  // console.table(arr)
  // let arr = [{ value: '<', type: 'prev' }, { value: 1, type: 'num' }, { value: 2, type: 'num' }, { value: 3, type: 'num' }, { value: ">", type: 'next' }]
  return (
    <div {...rest}>
      {showTotal && (
        <Total {...{ showTotal, allPage, range }} />
      )}
      {arr.map(item => {
        const PageItem = PageItemMapper[item.type]
        return <PageItem {...item} {...{ curPage, allPage, handlePageChange }} key={item.value} />
      })}
      {showSizeChanger && (
        <SizeChanger {...{ pageSizeOptions, pageSize: curSize, onChange: handleSizeChange }} />
      )}
      {showQuickJumper && (
        <QuickJumper {...{ curPage, handlePageChange }} />
      )}
    </div>
  )
}

{/* <div className=" h-8 min-w-8   t-blue-border inline-block se\  leading-8 "></div> */ }
const commonClass = classNames('inline-block h-8 min-w-8 border leading-8 text-center cursor-pointer select-none')
const NumItem = ({
  curPage,
  value,
  allPage,
  handlePageChange
}) => {
  const classString = classNames(commonClass, 'mr-2', {
    'border-blue-600 text-blue-600': curPage === value
  })
  const handleClick = e => {
    handlePageChange(value)
  }
  return (
    <span className={classString} onClick={handleClick}>
      {value}
    </span>
  )
}

const PrevItem = ({
  curPage,
  value,
  allPage,
  handlePageChange
}) => {
  const classString = classNames(commonClass, 'mr-2', {
    'border-blue-600 text-blue-600': curPage === value
  })
  const handleClick = e => {
    handlePageChange(curPage - 1)
  }
  return (
    <span className={classString} onClick={handleClick}>
      {value}
    </span>
  )
}

const NextItem = ({
  curPage,
  value,
  allPage,
  handlePageChange
}) => {
  const classString = classNames(commonClass, 'mr-2', {
    'border-blue-600 text-blue-600': curPage === value
  })
  const handleClick = e => {
    handlePageChange(curPage + 1)
  }
  return (
    <span className={classString} onClick={handleClick}>
      {value}
    </span>
  )
}

const JumpPrevItem = ({
  curPage,
  value,
  allPage,
  handlePageChange
}) => {
  const classString = classNames(commonClass, 'mr-2', {
    'border-blue-600 text-blue-600': curPage === value
  })
  const handleClick = e => {
    handlePageChange(Math.max(1, curPage - 5))
  }
  return (
    <span className={classString} onClick={handleClick}>
      {value}
    </span>
  )
}

const JumpNextItem = ({
  curPage,
  value,
  allPage,
  handlePageChange
}) => {
  const classString = classNames(commonClass, 'mr-2', {
    'border-blue-600 text-blue-600': curPage === value
  })
  const handleClick = e => {
    handlePageChange(Math.min(curPage + 5, allPage))
  }
  return (
    <span className={classString} onClick={handleClick}>
      {value}
    </span>
  )
}

const PageItemMapper = {
  'num': NumItem,
  'prev': PrevItem,
  'next': NextItem,
  'jumpPrev': JumpPrevItem,
  'jumpNext': JumpNextItem
}

const Total = ({
  showTotal,
  allPage,
  range
}) => {
  const classString = classNames('mr-2', {

  })
  return (
    <span className={classString}>{showTotal(allPage, range)}</span>
  )
}

const QuickJumper = ({
  handlePageChange,
  curPage
}) => {
  const [state, setState] = useState()
  const handleOnChange = (e) => setState(e.target.value)
  const handleKeyUp = (e) => {
    if (e.keyCode === 13) {
      setState('')
      handlePageChange(getNumValue(state, curPage))
    }
  }

  return (
    <>跳至<Input type="text" value={state} onKeyUp={handleKeyUp} onChange={handleOnChange} style={{ width: 50, marginLeft: 8, marginRight: 8 }} />页</>
  )
}

const SizeChanger = ({
  pageSizeOptions,
  pageSize,
  onChange
}) => {
  return (
    <Select
      options={getDisplayOptions(pageSizeOptions)}
      value={pageSize}
      onChange={onChange}
    />
  )
}

Pagination.defaultProps = {
  defaultCurrent: 1,
  defaultPageSize: 10,
  pageSizeOptions: [10, 20, 50, 100],
  showQuickJumper: false,
  RANGE: 2
}

// Pagination.propTypes = {
//   defaultCurrent: 1,
//   defaultPageSize: 10,
//   pageSizeOptions: [10, 20, 50, 100],
//   showQuickJumper: false,
//   RANGE: 2
// }

export default Pagination
